package com.affectu.user.action;

import java.util.List;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.security.Identity;

import com.affectu.dao.DAOBase;
import com.affectu.user.Role;
import com.affectu.user.User;

/*
 * 2008-8-30
 * @author daniel nathan
 */
@Name("authenticator")
public class Authenticator extends DAOBase {

	@Out(required = false, scope = ScopeType.SESSION)
	private User loginUser;
	@In
	Identity identity;
	private String url;

	@SuppressWarnings("unchecked")
	// 被identity.login()调用
	public boolean authenticate() {
		boolean flag = false;
		List results = em
				.createQuery(
						"select u from User u where u.email=#{identity.username} and u.password=#{identity.password}")
				.list();
		if (results.size() > 0) {
			this.loginUser = (User) results.get(0);
			for (Role role : this.loginUser.getRoles()) {
				identity.addRole(role.getName());
			}
			flag = true;
		}
		return flag;
	}

	public String login() {
		if (this.authenticate()) {
			url = "/passport/index.xhtml";
		} else {
			FacesMessages.instance().add("Email或者密码错误.");
		}
		return url;
	}

	public String logout() {
		try {
			this.identity.logout();
			this.removeCurrentUser();
		} catch (Exception ex) {
			this.logException(ex);
		}
		return "";
	}
}
